<template>
	<view class="almost-lottery" :style="{
		height:screenHeight+'px',
		background:backgroundColor
	}">
		<!-- head -->
		<view class="almost-lottery__head">
			<view v-if="noticeInfo">
				<u-notice-bar :text="noticeInfo.noticeContent" mode="link" @click="noticeDetail"></u-notice-bar>
			</view>
		</view>
		<!-- lottery -->
		<view class="almost-lottery__wheel">
			<view class="p30">
				<u-subsection :list="list" @change="changeCurrent" :current="current" activeColor="#F63857"
					bgColor="#fff3a3" inactiveColor="#F63857"></u-subsection>
				<view class="flex justify-center white bold" style="padding: 30rpx 30rpx 0 20rpx;">
					<view class="" v-if="current === 0">
						锈迹斑斑青铜一手
					</view>
					<view class="" v-if="current === 1">
						福气满满黄金一手
					</view>
					<view class="" v-if="current === 2">
						乾坤摩弄神之一手
					</view>
				</view>
			</view>
			<almost-lottery :lottery-size="lotteryConfig.lotterySize" :action-size="lotteryConfig.actionSize"
				:ring-count="2" :duration="1" :self-rotaty="false" :actionBg="actionBg" :lotteryBg="lotteryBg"
				:img-circled="true" :canvasCached="true" :prize-list="prizeList" :prize-index="prizeIndex"
				@reset-index="prizeIndex = -1" @draw-before="handleDrawBefore" @draw-start="handleDrawStart"
				@draw-end="handleDrawEnd" @finish="handleDrawFinish" v-if="prizeList.length" />
			<view class="almost-lottery__count">
				<text class="text">剩余免费抽奖 {{ freeNum }} 次</text>
			</view>

		</view>
		<!-- rule -->
		<view class="almost-lottery__rule" :style="{ background:backgroundColor }">
			<view class="rule-head">
				<view class="line"></view>
				<text class="title">活动规则</text>
				<view class="line"></view>
			</view>
			<view class="rule-body">
				<!-- 			<view class="item">
					<view class="number">1</view>
					<view class="text">
						<text>抽奖细则：</text>
						<text>每人每天拥有{{ freeNum }}次抽奖机会，每次消耗。</text>
					</view>
				</view> -->
				<view class="item item-rule">
					<view class="text">
						<!-- <text class="rule-title">🎯 奖励说明：</text> -->
						<view class="rule-block" v-if="current === 0">
							<text class="rule-level">🥉 青铜奖池</text>
							<text class="rule-detail">
								• 通过【个人中心签到】获取抽奖机会。<br>
								• 连续签到 3 天：获得 1 次抽奖机会。<br>
								• 累积签到 5 天：再获得 1 次抽奖机会。<br>
								• 会员与非会员均可参与。<br>
								• 签到次数每周一 0:00 重置。
							</text>
						</view>

						<view class="rule-block" v-if="current === 1">
							<text class="rule-level">🥈 黄金奖池</text>
							<text class="rule-detail">
								• 会员成功推广 2 名会员后，<br>
								• 每天自动获得 1 次抽奖机会。<br>
								• 仅限会员参与。<br>
								• 每日 0:00 重置。
							</text>
						</view>

						<view class="rule-block" v-if="current === 2">
							<text class="rule-level">💎 钻石奖池</text>
							<text class="rule-detail">
								• 会员推广 2 名会员后，<br>
								• 每周自动获得 1 次【超级奖池】抽奖机会。<br>
								• 仅限会员参与。<br>
								• 每周一 0:00 重置。
							</text>
						</view>
						<view class="" style="height: 100rpx;"></view>
					</view>
				</view>

			</view>
		</view>
	</view>
</template>

<script>
	import AlmostLottery from '@/uni_modules/almost-lottery/components/almost-lottery/almost-lottery.vue'
	import {
		clearCacheFile,
		clearStore
	} from '@/uni_modules/almost-lottery/utils/almost-utils.js'
	import {
		getPrizeListApi,
		saveUserPrizeApi,
		listNotice,
		getNotice
	} from '@/api/index.js'
	import {
		getUserInfo
	} from '@/utils/auth';
	import {
		getInfo
	} from '@/api/login'
	export default {
		name: 'Home',
		components: {
			AlmostLottery
		},
		data() {
			return {
				list: ['青铜', '黄金', '钻石'],
				current: 0,
				userInfo: {},
				// 开启调试模式
				isDev: true,
				// 以下是转盘配置相关数据
				lotteryConfig: {
					// 抽奖转盘的整体尺寸，单位rpx
					lotterySize: 600,
					// 抽奖按钮的尺寸，单位rpx
					actionSize: 200
				},

				// 以下是转盘 UI 配置
				// 转盘外环图，如有需要，请参考替换为自己的设计稿
				lotteryBg: require('@/static/images/almost-lottery__bg2x.png'),
				// 抽奖按钮图
				actionBg: require('@/static/images/action-bg.png'),

				// 以下是奖品配置数据
				// 奖品数据
				prizeList: [],
				// 奖品是否设有库存
				onStock: false,
				// 中奖下标
				prizeIndex: -1,

				// 是否正在抽奖中，避免重复触发
				prizeing: false,

				// 以下为中奖概率有关数据
				// 是否由前端控制概率，默认不开启，强烈建议由后端控制
				onFrontend: true,
				// 权重随机数的最大值
				prizeWeightMax: 100,
				// 权重数组
				prizeWeightArr: [],

				// 以下为业务需求有关示例数据
				// 金币余额
				goldCoin: 20,
				// 当日免费抽奖次数余额
				freeNum: 0,
				// 每次消耗的金币数
				goldNum: 20,
				// 每天免费抽奖次数
				freeNumDay: 0,
				lotteryChancesVO: {
					levelOneCount: 0,
					levelThreeCount: 0,
					levelTwoCount: 0
				},
				noticeInfo: null,
				backgroundColor: '#ff2f4c',
				screenHeight: ''
			}
		},
		computed: {

		},
		onLoad() {
			this.getUserInfo();
			this.getList();
			this.prizeList = [];
			this.getPrizeList();
			const res = uni.getSystemInfoSync();
			console.log(res, 'res');
			this.screenHeight = res.windowHeight;

		},
		onUnload() {
			uni.hideLoading()
		},
		methods: {
			// 点击通告详情
			noticeDetail() {
				// console.log(this.noticeInfo);
				uni.showModal({
					title: this.noticeInfo.noticeTitle,
					content: this.noticeInfo.noticeContent,
					confirmText: '我知道了',
					showCancel: false
				})
			},
			getList() {
				listNotice({
					pageNum: 1,
					pageSize: 9999
				}).then(response => {
					console.log(response, 'response');
					if (response.rows.length > 0) {
						const list = response.rows.reverse();
						console.log(list[0]);
						this.noticeInfo = list[0]
						const isLogin = uni.getStorageSync('isLogin');
						console.log(isLogin, 'isLogin');
						if (isLogin) {
							this.noticeDetail();
							uni.setStorageSync('isLogin', false)
						}
					} else {
						this.noticeInfo = null
					}
				})
			},
			// 获取用户信息
			getUserInfo() {
				getInfo().then(res => {
					console.log(res, '获取用户信息-lotteryChancesVO');
					if (res.code === 200) {
						this.userInfo = res.user;
						this.lotteryChancesVO = res.lotteryChancesVO || {
							levelOneCount: 0,
							levelThreeCount: 0,
							levelTwoCount: 0
						};
						// this.freeNum = res.lotteryChancesVO.levelTwoCount || 0;
						// this.freeNum = 2;
						this.setCount();
					}
				})
			},
			setCount() {
				if (this.current === 0) {
					this.freeNum = this.lotteryChancesVO.levelOneCount;
					this.backgroundColor = '#ff2f4c';
				} else if (this.current === 1) {
					this.freeNum = this.lotteryChancesVO.levelTwoCount;
					this.backgroundColor = '#ff2f4c';
				} else {
					this.freeNum = this.lotteryChancesVO.levelThreeCount;
					this.backgroundColor = '#409eff';
				}
			},
			// 切换
			async changeCurrent(val) {
				console.log(val, 'changeCurrent');
				this.current = val;
				this.prizeList = []
				this.getPrizeList()
				await this.getUserInfo();
				this.setCount();
			},
			// 重新生成
			handleInitCanvas() {
				clearCacheFile()
				clearStore()
				this.prizeList = []
				this.getPrizeList()
			},
			// 通过 popup 打开
			handleCheckPopup() {
				uni.navigateTo({
					url: '/pages/popup/popup'
				})
			},
			// 获取奖品列表
			async getPrizeList() {
				// console.log('获取奖品列表', res)
				let resp = await getPrizeListApi(this.current + 1);
				console.log(resp);
				if (resp.code === 200) {
					resp = resp.rows.map((item) => ({
						...item,
						prizeId: item.id,
						prizeName: `${item.name}(${item.prizeType == 1?'测试':item.prizeType == 2?'积分': item.prizeType == 3?'实物':'优惠券'})`,
						prizeStock: 999,
						prizeWeight: item.winningProbability,
						prizeImage: require('@/static/images/git.png'),
					}));
					console.log(resp, 'new');
					this.prizeList = resp;
					if (this.onFrontend) {
						// 生成权重数组并排序取得最大值
						this.prizeWeightArr = this.prizeList.map(item => item.prizeWeight)
						let prizeWeightArrSort = [...this.prizeWeightArr]
						prizeWeightArrSort.sort((a, b) => b - a)
						// 开放自定义权重最大值，没有自定义则取权重数组中的最大值
						this.prizeWeightMax = this.prizeWeightMax > 0 ? this.prizeWeightMax : prizeWeightArrSort[0]
					}
				} else {
					uni.hideLoading()
					uni.showToast({
						title: '获取奖品失败',
						mask: true,
						icon: 'none'
					})
				}
			},
			// 抽奖开始之前
			handleDrawBefore(callback) {
				console.log('抽奖开始之前')
				let flag = false
				console.log(this.freeNum, 'this.freeNum');
				// 还有免费数次或者剩余金币足够抽一次|| this.goldCoin >= this.goldNum
				if (this.freeNum > 0) {
					if (this.freeNum > 0) {
						this.freeNum--
					}
					flag = true
				} else {
					flag = false
					uni.showToast({
						title: '抽奖次数不足',
						icon: 'none'
					})
				}
				callback(flag)
			},
			// 本次抽奖开始
			handleDrawStart() {
				console.log('触发抽奖按钮')
				if (this.prizeing) return
				this.prizeing = true
				this.tryLotteryDraw()
			},
			// 尝试发起抽奖
			tryLotteryDraw() {
				console.log('旋转开始，获取中奖下标......')
				// 判断是否由前端控制概率
				if (this.onFrontend) {
					this.localGetPrizeIndex()
				} else {
					this.remoteGetPrizeIndex()
				}
			},
			// 前端根据后端返回的 winningProbability 控制中奖概率
			localGetPrizeIndex() {
				console.warn('### 当前处于前端按后端概率计算中奖结果 ###');

				if (!this.prizeList.length) {
					console.warn('奖品列表为空');
					return;
				}

				// 提取权重数组
				const weights = this.prizeList.map(item => Number(item.prizeWeight) || 0);
				const total = weights.reduce((a, b) => a + b, 0);
				console.log(weights, 'weights');
				console.log(total, 'total');
				if (total <= 0) {
					console.warn('奖品权重总和为 0，无法计算中奖概率');
					this.prizeIndex = Math.floor(Math.random() * this.prizeList.length);
					return;
				}
				// 随机一个区间值
				const rand = Math.random() * total;
				let cumulative = 0;
				let selectedIndex = 0;

				for (let i = 0; i < weights.length; i++) {
					cumulative += weights[i];
					if (rand <= cumulative) {
						selectedIndex = i;
						break;
					}
				}

				this.prizeIndex = selectedIndex;
				// console.log(
				// 	'本次抽中奖品 =>',
				// 	this.prizeList[this.prizeIndex].prizeName,
				// 	'（概率：' + this.prizeList[this.prizeIndex].prizeWeight + '）'
				// );
			},

			// 远程请求接口获取中奖下标
			// 大哥，这里只是模拟，别告诉我你不会对接自己的接口
			remoteGetPrizeIndex() {
				console.warn('###当前处于模拟的请求接口，并返回了中奖信息###')
				// 模拟请求接口获取中奖信息
				let stoTimer = setTimeout(() => {
					stoTimer = null
					let list = [...this.prizeList]
					// 这里随机产生的 prizeId 是模拟后端返回的 prizeId
					let prizeId = Math.floor(Math.random() * list.length + 1)
					console.log(prizeId, '中奖id');
					// 拿到后端返回的 prizeId 后，开始循环比对得出那个中奖的数据
					for (let i = 0; i < list.length; i++) {
						let item = list[i]
						if (item.prizeId === prizeId) {
							// 中奖下标
							this.prizeIndex = i
							break
						}
					}
					console.log(this.prizeIndex, 'this.prizeIndex--中奖index');
					console.log('本次抽中奖品 =>', this.prizeList[this.prizeIndex].prizeName)
					// 如果奖品设有库存
					if (this.onStock) {
						console.log('本次奖品库存 =>', this.prizeList[this.prizeIndex].prizeStock)
					}
				}, 200)
			},
			// 本次抽奖结束
			async handleDrawEnd() {
				console.log('旋转结束，执行拿到结果后到逻辑')
				console.log(this.prizeList[this.prizeIndex], '抽中的奖品信息--本次抽奖结束');
				// 旋转结束后，开始处理拿到结果后的逻辑
				let prizeName = this.prizeList[this.prizeIndex].prizeName
				let tipContent = ''

				if (prizeName === '谢谢参与') {
					tipContent = '很遗憾，没有中奖，请再接再厉！'
				} else {
					try {
						const resp = await saveUserPrizeApi({
							prizeId: this.prizeList[this.prizeIndex].prizeId,
							userId: this.userInfo.userId,
						})
						console.log(resp, 'resp');
						if (resp.code === 200) {
							tipContent =
								`恭喜您，获得 ${prizeName},奖品类型为${resp.data.prizeType == 1?'测试':resp.data.prizeType == 2?'积分': resp.data.prizeType == 3?'实物':'优惠券'},价值积分${resp.data.prizeAmount}`
						} else {
							tipContent = `恭喜您，获得 ${prizeName} ！`
						}
						uni.showModal({
							content: tipContent,
							showCancel: false,
							complete: () => {
								this.prizeing = false
							}
						})
						this.changeCurrent(this.current);
						await this.getUserInfo();
					} catch {
						console.log('出错了');
						this.prizeing = false
					}
				}

			},
			// 抽奖转盘绘制完成
			handleDrawFinish(res) {
				console.log('抽奖转盘绘制完成', res)
				if (res.ok) {
					// 计算结束绘制的时间
					if (console.timeEnd) {
						console.timeEnd('绘制转盘用时')
					}
				}
			}
		},
	}
</script>

<style lang="scss" scoped>
	page {
		// height: 100vh;
		// overflow: auto;
		// background: rgb(255, 47, 76);
	}

	.almost-lottery {

		// flex: 1;
		// background: #FF893F;
	}

	.almost-lottery__head {
		position: relative;
		width: 100%;
		height: 50px;
		// border: 1rpx solid #000;
		// background: url('@/static/images/lottery/top-bg.png') no-repeat center center/cover;

		.action {
			position: relative;
			top: 60rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			width: 480rpx;
			height: 88rpx;
			line-height: 88rpx;
			margin: 0 auto;
			color: #FFFFFF;
			font-size: 32rpx;
			background-color: rgba(255, 136, 61, 1);
			border-radius: 44rpx;
		}

		.action-shadow {
			box-shadow: 0px 14rpx 0px 0px rgba(235, 112, 36, 1);
		}

		.gold {
			width: 44rpx;
			height: 44rpx;
			margin-right: 10rpx;
			background-repeat: no-repeat;
			background-position: center center;
			background-size: contain;
			background-image: url("~static/images/lottery/gold.png");

			@media (-webkit-min-device-pixel-ratio: 2),
			(min-device-pixel-ratio: 2) {
				background-image: url("~static/images/lottery/gold@2x.png");
			}

			@media (-webkit-min-device-pixel-ratio: 3),
			(min-device-pixel-ratio: 3) {
				background-image: url("~static/images/lottery/gold@3x.png");
			}
		}

		.num {
			color: #F9FC31;
		}

		.tip {
			position: relative;
			top: 428rpx;
			color: #FFFFFF;
			font-size: 24rpx;
			text-align: center;
		}
	}

	.almost-lottery__wheel {
		text-align: center;

		.almost-lottery__count {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			text-align: center;
			padding: 20rpx 0;
		}

		.text {
			color: #FFFFFF;
			font-size: 24rpx;
		}
	}

	.almost-lottery__rule {
		padding: 0 28rpx;
		color: #FFF8CB;

		.rule-head {
			display: flex;
			justify-content: space-around;
			align-items: center;
			margin: 0rpx 0;

			.line {
				flex: 1;
				height: 1px;
				background-color: #FFF3A5;
			}

			.title {
				width: 280rpx;
				color: #F63857;
				line-height: 70rpx;
				text-align: center;
				margin: 0 20rpx;
				border-radius: 8rpx;
				background-image: linear-gradient(0deg, rgba(255, 242, 158, 1), rgba(255, 244, 168, 1));
			}
		}

		.rule-body {
			color: #FFF8CB;
			font-size: 24rpx;
			padding: 10rpx 0 40rpx;

			.item {
				display: flex;
				margin-bottom: 10rpx;
			}

			.number {
				position: relative;
				top: 4rpx;
				width: 28rpx;
				height: 28rpx;
				line-height: 28rpx;
				text-align: center;
				color: #F63857;
				background: #FFF8CB;
				border-radius: 50%;
				margin-right: 10rpx;
			}

			.text {
				flex: 1;
			}

			.item-rule .text {
				display: flex;
				flex-direction: column;
			}
		}
	}

	.almost-lottery__action-dev {
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		width: 400rpx;
		height: 80rpx;
		border-radius: 10rpx;
		text-align: center;
		background-color: red;
		margin: 0 auto 40rpx;

		.text {
			color: #FFFFFF;
			font-size: 28rpx;
		}
	}

	.almost-lottery__popup-wrap {
		flex: 1;
		display: flex;
		justify-content: center;
		align-items: center;

		.almost-lottery {
			background: transparent;
		}
	}

	.item-rule {
		margin-top: 20rpx;
	}

	.item-rule .text {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.rule-title {
		font-size: 30rpx;
		font-weight: bold;
		color: #fff3a3;
	}

	.rule-block {
		background: rgba(255, 255, 255, 0.1);
		border-radius: 12rpx;
		padding: 20rpx;
	}

	.rule-level {
		font-size: 26rpx;
		color: #ffdf67;
		font-weight: 600;
		display: block;
		margin-bottom: 8rpx;
	}

	.rule-detail {
		font-size: 24rpx;
		color: #fff8cb;
		line-height: 1.6;
	}

	::v-deep .u-notice__content__text text {
		font-size: 24px !important;
	}
</style>